/**
 * author:Administrator
 * date:2016/3/2
 * desc:TODO
 */
"use strict";

let Router = require('koa-router')
  , __pathPrefix = '/api/v1/user'
  , router = new Router({prefix: __pathPrefix});
module.exports = router.routes();
console.log('router:' + __pathPrefix + ',file=' + __filename);

let koabody = require('koa-better-body')();
let appUtil = require('../../common/appUtil.js');
let FormatOutput = require('../../common/FormatOutput.js');
let FormatError = require('../../common/FormatError.js');

let platformService = require('../../service/platform');
/**
 * 用户 注册
 * name,pwd
 */
router.post('/register', koabody, function*() {
  let fields = this.request.body.fields;
  let name = fields.name;
  let pwd = fields.pwd;
  if (!name || !pwd) {
    return this.body = FormatOutput.payloadOrError(null, FormatError.E_register_user);
  }

  this.body = yield platformService.userRegister(name, pwd);

});

/**
 * 用户登录
 * name,pwd
 */
router.post('/login', koabody, function*() {
  let fields = this.request.body.fields;
  let name = fields.name;
  let pwd = fields.pwd;
  if (!name || !pwd) {
    return this.body = FormatOutput.payloadOrError(null, FormatError.E_login);
  }

  let retObj = yield platformService.userLogin(name, pwd);
  if (retObj.isOk()) {
    let user = retObj.getPayload();
    let token = user.token = appUtil.genToken(user);
    yield appUtil.saveToken(token, user);
  }
  console.log(typeof retObj, retObj);
  this.body = retObj;
});
